package com.ruoyi.system.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;

/*
初始化器，channel注册之后会执行里面的相应的初始化方法
 */
public class HelloNettyServerInitializer extends ChannelInitializer<SocketChannel> {


    private CustomHandler customHandler;

    public HelloNettyServerInitializer(CustomHandler customHandler) {
        this.customHandler = customHandler;
    }

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        //通过SocketChannel去获取对应的管道
        ChannelPipeline pipeline = channel.pipeline();
        //通过管道添加handler
        //new HttpServerCodec()是由netty自己提供的助手类，可以理解为拦截器
        //当请求到服务器，我们需要解码，响应到客户端需要做编码
        //pipeline.addLast("HttpServerCodec", new HttpServerCodec());
        //添加自定义助手类，给客户端浏览器渲染hello netty~
        //pipeline.addLast("string", new StringDecoder());
        pipeline.addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
        pipeline.addLast("encoder", new StringEncoder(StandardCharsets.UTF_8));
        pipeline.addLast("CunstomHandler", customHandler);
        //pipeline.addLast("string", new StringEncoder());
    }
}
